package cn.itcast.nems.listener;

import cn.hutool.core.lang.Assert;
import cn.itcast.ic.common.exception.v2.BizExceptionProducer;
import cn.itcast.nems.common.enumeration.NemsErrorBodyEnum;
import com.alibaba.fastjson.JSON;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
 * <p>
 * 订单消息策略处理类
 * </p>
 *
 * @author zhouwei
 * @since 2023/12/7 10:34 AM
 **/
@Component
@Slf4j
public class MessageListenerProcessor {

    /**
     * 继承策略接口的业务实现类实例
     */
    @Autowired
    private Set<NemsMessageListener> OrderMessageConsumerStrategySet;

    Map<String, NemsMessageListener> map;

    @PostConstruct
    public void init() {
        Assert.notNull(OrderMessageConsumerStrategySet, BizExceptionProducer.produce(NemsErrorBodyEnum.STRATEGY_EXIST, "订单消费策略"));
        map = OrderMessageConsumerStrategySet.stream().collect(Collectors.toMap(NemsMessageListener::getTagName, Function.identity()));
        log.info("【初始化订单消费策略】详情：{}", JSON.toJSONString(map.keySet()));
    }

    public void process(String tagName, String body) {
        NemsMessageListener listener = map.get(tagName);
        log.info("【消息处理】 Tag Name：{}，获取的监听实现类是否为空：{} , " ,tagName,Objects.isNull(listener) );
        if (Objects.nonNull(listener)) {
            listener.processMessage(body);
        }
    }

}
